//
//  ios_File.mm
//  Prism
//
//  Created by Bas du Pre on 21-05-11.
//  Copyright 2011 UU. All rights reserved.
//

#include "global.h"
#if PRISM_TARGET_SDL
#include "sdl/sdl_global.h"

#include "File.h"
#if PRISM_OS_WIN == 0
#include <unistd.h>
#endif
#include <stdlib.h>

Prism::String Prism::File::native_getResourcesPath() {
	#if PRISM_OS_MAC
    
    return native_macResourcesPath();
    
	#elif PRISM_OS_LINUX_X11 || PRISM_OS_WIN
	
	return Prism::File(Prism::File::native_exePath()).dirname();
	
	#endif
	
	return Prism::String("");
}

int Prism::File::argc = 0;
char** Prism::File::argv;

void Prism::File::native_setArgcArgv(int argc, char** argv) {
    Prism::File::argc = argc;
    Prism::File::argv = argv;
}

Prism::String Prism::File::native_exePath() { 
	static Prism::String _exePath = "";
    #if PRISM_OS_LINUX_X11
    if (_exePath == Prism::String("")) {
        const int size = 2048;
        char buffer[size] = "/proc/self/exe";
        char buffer2[size] = {0};
        ssize_t ret;
        do {
            memset(&buffer2, 0, size);
            ret = readlink((const char*)&buffer, (char*)&buffer2, size);
            if (ret > 0) memcpy(&buffer, &buffer2, ret);
        }while (ret > 0);
        
        _exePath = Prism::String((char*)&buffer);
    }
    
    #elif PRISM_OS_WIN
    if (_exePath == Prism::String("")) {
        TCHAR szPath[MAX_PATH] = {0};

        if(!GetModuleFileName(NULL, szPath, MAX_PATH))
        {
            PRISM_ERROR("Cannot get executable location (%d)", GetLastError());
            return _exePath;
        }
        _exePath = Prism::String(szPath);
    }
    
    #else
    
    if (_exePath == Prism::String("")) {
        _exePath = Prism::String(Prism::File::argv[0]);
    }
    
    #endif
    
    return _exePath;
}

#endif
